import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mall/constant/app_colors.dart';
import 'package:mall/constant/app_strings.dart';
import 'package:mall/constant/text_style.dart';
import 'package:mall/modules/model/fill_in_order_entity.dart';
import 'package:mall/modules/model/order_list_entity.dart';
import 'package:mall/modules/sc/order_sc.dart';
import 'package:mall/modules/service/mine_service.dart';
import 'package:mall/ui/page/goods/widgets/order_goods_list_widget.dart';
import 'package:mall/ui/page/goods/order/widets/placeholder_in_order_widget.dart';
import 'package:mall/ui/widgets/divider_line.dart';
import 'package:mall/utils/alert/app_alert.dart';
import 'package:mall/utils/list_placeholder_component/list_placeholder_component.dart';
import 'package:mall/router/navigator_util.dart';
import 'package:mall/utils/refresh/refresh_widget.dart';
import 'package:mall/utils/refresh/warp_refresh_controller.dart';

class OrderListPage extends StatefulWidget {
  final int showType;

  OrderListPage({required this.showType});

  @override
  _OrderListPageState createState() => _OrderListPageState();
}

class _OrderListPageState extends State<OrderListPage> with AutomaticKeepAliveClientMixin {
  late final sc_orderList = Get.put(OrderListSc(), tag: widget.showType.toString());
  late final _refreshController = WarpRefreshController(loadState: sc_orderList.loadState);
  @override
  void initState() {
    super.initState();
    sc_orderList.orderType = widget.showType;
  }

  @override
  void dispose() {
    super.dispose();
    _refreshController.dispose();
  }

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return _contentView();
  }

  Widget _contentView() {
    return Obx(
      () => RefreshComponent(
        controller: _refreshController,
        onLoading: () => sc_orderList.loadMoreData(),
        onRefresh: () => sc_orderList.refreshData(),
        child: WrappedListPlaceholderComponent.widget(
          emptyWidget: PlaceholderInOrderWidget(),
          sc: sc_orderList,
          builder: (p0) => ListView.builder(
            itemCount: p0.length,
            itemBuilder: (BuildContext context, int index) {
              return _orderItemView(p0[index]);
            },
          ),
        ),
      ),
    );
  }

  Widget _orderItemView(OrderEntity order) {
    final goodsList = order.goodsList ?? [];
    return Card(
        color: AppColors.C_FFFFFF,
        child: InkWell(
            onTap: () => NavigatorUtil.goOrderDetailPage(context, order.id),
            child: Container(
              margin: EdgeInsets.symmetric(horizontal: 15, vertical: 15),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  //订单号和状态
                  Row(
                    children: <Widget>[
                      //订单状态
                      Text(
                        '订单号:${order.orderSn ?? ""}',
                        style: TextStyle(color: AppColors.C_222222, fontSize: 13),
                      ),
                      //订单状态
                      Spacer(),
                      //订单状态
                      Text("${order.orderStatusText}", style: TextStyle(color: Color(0xffFC2f1c), fontSize: 13)),
                    ],
                  ),
                  SizedBox(height: 10),
                  //商品
                  OrderGoodsListWidget(checkedGoodsList: goodsList),

                  SizedBox(height: 5),
                  DividerLineView(),
                  SizedBox(height: 5),
                  //订单金额
                  Row(
                    children: [
                      //商品数量
                      Text(
                          AppStrings.MINE_ORDER_TOTAL_GOODS +
                              "${goodNumber(order.goodsList ?? [])}" +
                              AppStrings.MINE_ORDER_GOODS_TOTAL,
                          style: FMTextStyle.color_999999_size_12),

                      SizedBox(width: 10),
                      //总价
                      Text(AppStrings.MINE_ORDER_PRICE + "${order.actualPrice}",
                          style: FMTextStyle.color_ff5722_size_13),

                      Spacer(),

                      //操作按钮
                      Row(
                        children: [
                          //删除
                          _optionBtn(
                            title: AppStrings.DELETE,
                            titleColor: AppColors.C_222222,
                            borderColor: AppColors.C_DBDBDB,
                            visible: order.handleOption?.delete ?? false,
                            onTap: () => _showDialog(2, order.id),
                          ),
                          //取消
                          _optionBtn(
                            title: AppStrings.CANCEL,
                            titleColor: AppColors.C_222222,
                            borderColor: AppColors.C_DBDBDB,
                            visible: order.handleOption?.cancel ?? false,
                            onTap: () => _showDialog(1, order.id),
                          ),
                        ],
                      )
                    ],
                  )
                ],
              ),
            )));
  }

  Widget _optionBtn({
    String? title,
    Color titleColor = AppColors.C_222222,
    Color borderColor = AppColors.C_DBDBDB,
    bool visible = false,
    Function()? onTap,
  }) {
    return Visibility(
      visible: visible,
      child: InkWell(
        onTap: onTap,
        child: Container(
          height: 28,
          margin: EdgeInsets.only(left: 10),
          padding: EdgeInsets.symmetric(horizontal: 13),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(14),
            border: Border.all(color: borderColor, width: 0.5),
          ),
          alignment: Alignment.center,
          child: Text(
            title ?? '',
            style: TextStyle(color: titleColor, fontSize: 12),
          ),
        ),
      ),
    );
  }

  _showDialog(int action, int? orderId) {
    if (orderId == null) {
      return;
    }

    AppAlert.showAlertDialog(
        content: action == 1 ? AppStrings.MINE_ORDER_CANCEL_TIPS : AppStrings.MINE_ORDER_DELETE_TIPS,
        onConfirm: () {
          if (action == 1) {
            MineService.cancelOrder(orderId);
          } else {
            MineService.deleteOrder(orderId);
          }
        });
  }

  int goodNumber(List<FillInOrderCheckedgoodslist> order) {
    int number = 0;
    order.forEach((good) {
      number += (good.number ?? 0);
    });
    return number;
  }
}
